package com.figure.web.controller.item;

import com.alibaba.fastjson.JSON;
import com.figure.common.utils.StringUtil;
import com.figure.service.dto.PageDto;
import com.figure.service.dto.item.*;
import com.figure.service.provide.item.ICategoryService;
import com.figure.service.provide.item.IItemService;
import com.figure.web.controller.BaseController;
import com.figure.web.util.APIResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;


/**
 * Created by Weber on 1/19/2016.
 */
@Controller
@RequestMapping("/admin/item")
public class ItemBackedController extends BaseController{

    private static Logger logger = LoggerFactory.getLogger(ItemBackedController.class);

    @Autowired
    private IItemService itemService;

    @Autowired
    private ICategoryService categoryService;

    //open_iid,title,nick,pic_url,price,commission,commission_rate,commission_num,commission_volume,seller_credit_score,item_location,volume,seller_id,title,coupon_rate,coupon_price,coupon_start_time,coupon_end_time,shop_type,promotion_price
    @RequestMapping(value = {"/addAtbItems"})
    public APIResult addAtbItems(String area, String autoSend, String cashCoupon, Long cid, String endCommissionNum,String endCommissionRate,String endCredit,
                                 String endPrice,String endTotalnum,@RequestParam(value = "fields", required = true)String fields,String guarantee,String keyword,String mallItem,
                                 String onemonthRepair,String overseasItem,String pageNo, String pageSize, String realDescribe,String sevendaysReturn,
                                 String sort,String startCommissionNum,String startCommissionRate,String startCredit,String startPrice,
                                 String startTotalnum,String supportCod, String vipCard) {
        Long pn = null;
        Long ps = null;
        try {
            if(StringUtil.isEmpty(pageNo)){
                pn = new Long(1);
            }else {
                pn = new Long(pageNo);
            }
            if(StringUtil.isEmpty(pageSize)){
                ps = new Long(50);
            }else {
                ps = new Long(pageSize);
            }

            itemService.addAtbItems(area, autoSend,cashCoupon,cid,endCommissionNum,endCommissionRate,endCredit,endPrice,endTotalnum
                    ,fields,
                    guarantee,keyword,mallItem,onemonthRepair,overseasItem,pn, ps,realDescribe,sevendaysReturn,
                    sort,startCommissionNum,startCommissionRate,startCredit,startPrice,startTotalnum,supportCod,vipCard);
        } catch (Exception e) {
            logger.error("插入商品异常！" + e.getMessage());
            e.printStackTrace();
            return APIResult.failResult(100, "插入商品异常！");
        }
        return APIResult.okResult(null);
    }

    @RequestMapping(value = {"/getAtbItems"})
    public APIResult getAtbItems(ModelMap modelMap,String area, String autoSend, String cashCoupon, Long cid, String endCommissionNum,
                                 String endCommissionRate, String endCredit, String endPrice, String endTotalnum, String fields,
                                 String guarantee, String keyword, String mallItem, String onemonthRepair, String overseasItem,
                                 String pageNo, String pageSize, String realDescribe, String sevendaysReturn, String sort, String startCommissionNum,
                                 String startCommissionRate, String startCredit, String startPrice, String startTotalnum, String supportCod, String vipCard) {
        Long pn = null;
        Long ps = null;
        PageDto<AtbItemDto> list = null;
        try {
            if(StringUtil.isEmpty(pageNo)){
                pn = new Long(1);
            }else {
                pn = new Long(pageNo);
            }
            if(StringUtil.isEmpty(pageSize)){
                ps = new Long(20);
            }else {
                ps = new Long(pageSize);
            }
            fields="open_iid,title,nick,pic_url,price,commission,commission_rate,commission_num,commission_volume,seller_credit_score,item_location,volume,seller_id,title,coupon_rate,coupon_price,coupon_start_time,coupon_end_time,shop_type,promotion_price";
            list = itemService.getAtbItems(area, autoSend, cashCoupon, cid, endCommissionNum,
                    endCommissionRate, endCredit, endPrice, endTotalnum, fields,
                    guarantee, keyword, mallItem, onemonthRepair, overseasItem,
                    pn, ps, realDescribe, sevendaysReturn, sort, startCommissionNum,
                    startCommissionRate, startCredit, startPrice, startTotalnum, supportCod, vipCard);
//            if(null!=list){
//                modelMap.put("total", list.getTotal());
//            }else {
//                modelMap.put("total", "0");
//            }
        } catch (Exception e) {
            logger.error("查询商品异常！" + e.getMessage());
            e.printStackTrace();
            return APIResult.failResult(101, "查询商品异常！");
//            faile(101, "查询商品异常！", modelMap);
//            return "fail";
        }
        return APIResult.okResult(list);
//        ok(list.getResultList(), modelMap);
//        return "success";
    }

    @RequestMapping(value = {"/addAtbItemsCoupon"})
    public APIResult addAtbItemsCoupon(String pageNo, String pageSize, String keyword) {
        Long pn = null;
        Long ps = null;
        try {
            if(StringUtil.isEmpty(pageNo)){
                pn = new Long(1);
            }else {
                pn = new Long(pageNo);
            }
            if(StringUtil.isEmpty(pageSize)){
                ps = new Long(50);
            }else {
                ps = new Long(pageSize);
            }

            itemService.addAtbItemsCoupon(null, null, null, null, null, null, null, null, null,
                    "open_iid,title,nick,pic_url,price,commission,commission_rate,commission_num,commission_volume,seller_credit_score,item_location,volume,coupon_price,coupon_rate,coupon_start_time,coupon_end_time,shop_type",
                    keyword, pn, ps, null,
                    null, null, null, null, null, null, null);
        } catch (Exception e) {
            logger.error("插入爱淘宝折扣商品异常！" + e.getMessage());
            e.printStackTrace();
            return APIResult.failResult(102, "插入爱淘宝折扣商品异常！");
        }
        return APIResult.okResult(null);
    }

    @RequestMapping(value = {"/saveItemCategory"})
    public APIResult saveItemCategory(ModelMap modelMap, String itemList, String categoryId) {
        if(StringUtil.isEmpty(itemList) || StringUtil.isEmpty(categoryId)){
            return APIResult.failResult(107, "参数不能为空");
        }
        List<FigureItemDto> list = JSON.parseArray(itemList, FigureItemDto.class);
//        Long cid = null;
        Long[] cids = null;
        try {
            if(null!=list && list.size()>0){
                String[] cates = categoryId.split(",");
                if(null!=cates && cates.length>0){
                    cids = new Long[cates.length];
                    for (int i=0; i<cates.length;i++){
                        cids[i] = new Long(cates[i]);
                    }
                }
//                if(StringUtil.isNotEmpty(categoryId)){
//                    cid = new Long(categoryId);
//                }
                itemService.saveItemCategory(list, cids);
            }
        } catch (Exception e) {
            logger.error("商品设置异常！" + e.getMessage());
            e.printStackTrace();
            return APIResult.failResult(101, "商品设置异常！");
//            faile(105, "查询商品异常！", modelMap);
//            return "fail";
        }
//        return APIResult.okResult(list);
//        ok(list.getResultList(), modelMap);
//        return "success";
        return APIResult.okResult(null);
    }

    @RequestMapping(value = {"/saveHotItems"})
    public APIResult saveHotItems(ModelMap modelMap, String itemList) {
        if(StringUtil.isEmpty(itemList)){
            return APIResult.failResult(108, "参数不能为空");
        }
        List<FigureItemDto> list = JSON.parseArray(itemList, FigureItemDto.class);
        try {
            if(null!=list && list.size()>0){
                itemService.saveHotItems(list);
            }
        } catch (Exception e) {
            logger.error("商品设置异常！" + e.getMessage());
            e.printStackTrace();
            return APIResult.failResult(101, "商品设置异常！");
//            faile(105, "查询商品异常！", modelMap);
//            return "fail";
        }
//        return APIResult.okResult(list);
//        ok(list.getResultList(), modelMap);
//        return "success";
        return APIResult.okResult(null);
    }

    @RequestMapping(value = {"/saveRecommendItems"})
    public APIResult saveRecommendItems(ModelMap modelMap, String itemList) {
        if(StringUtil.isEmpty(itemList)){
            return APIResult.failResult(108, "参数不能为空");
        }
        List<FigureItemDto> list = JSON.parseArray(itemList, FigureItemDto.class);
        try {
            if(null!=list && list.size()>0){
                itemService.saveRecommendItems(list);
            }
        } catch (Exception e) {
            logger.error("商品设置异常！" + e.getMessage());
            e.printStackTrace();
            return APIResult.failResult(101, "商品设置异常！");
//            faile(105, "查询商品异常！", modelMap);
//            return "fail";
        }
//        return APIResult.okResult(list);
//        ok(list.getResultList(), modelMap);
//        return "success";
        return APIResult.okResult(null);
    }

    @RequestMapping(value = {"/saveBanner"})
    public APIResult saveBanner(ModelMap modelMap, String id, String name, String type,
                                String status, String imgUrl, String content) {
        if(StringUtil.isEmpty(type)){
            return APIResult.failResult(112, "参数type不能为空");
        }
        if(StringUtil.isEmpty(content)){
            return APIResult.failResult(111, "参数content不能为空");
        }
        if(StringUtil.isEmpty(content)){
            return APIResult.failResult(113, "参数name不能为空");
        }

        try {
            //类别0:商品id，1:分类id，2:url
            if("0".equals(type)){
                FigureItemDto figureItemDto = itemService.getFigureItem(content);
                if(null==figureItemDto){
                    return APIResult.failResult(114, "商品不存在，openIid：" + content);
                }
            }else if("1".equals(type)){
                CategoryDto dto = categoryService.getCategory(new Long(content));
                if(null==dto){
                    return APIResult.failResult(115, "类目不存在，id：" + content);
                }
            }
            BannerDto dto = new BannerDto();
            if(StringUtil.isNotEmpty(id)){
                dto.setId(new Long(id));
            }
            dto.setContent(content);
            dto.setType(type);
            dto.setStatus(null==status?"0":status);
            dto.setName(name);
            dto.setImgUrl(imgUrl);

            itemService.saveBanner(dto);
        } catch (Exception e) {
            logger.error("保存banner信息异常！" + e.getMessage());
            e.printStackTrace();
            return APIResult.failResult(101, "保存banner信息异常！");
//            faile(105, "查询商品异常！", modelMap);
//            return "fail";
        }
//        return APIResult.okResult(list);
//        ok(list.getResultList(), modelMap);
//        return "success";
        return APIResult.okResult(null);
    }
}
